import {setLoginSession, getLoginSession, removeLoginSession} from '../../../config/loginSession';
import {toast} from '../../../components/GlobalToast';
import {loginMix, loginByToken} from '../services/loginService';
import {Actions} from 'react-native-router-flux';

const defaultState = {
	
	account: '',
	password: '',
	
};

export default {

	namespace: 'login',
	
	state: {...defaultState},
	
	reducers: {
		
		changeAccount(state, {payload}) {
			return {...state, ...{account: payload}};
		},
		
		changePassword(state, {payload}) {
			return {...state, ...{password: payload}};
		},
		
	},
	
	effects: {
		
		*checkLogin(action, {select}) {
			let loginSession = yield getLoginSession();
			if(loginSession) {
				let loginState = yield select(state => (state.login));
				yield Actions.replace(loginState.loginRedirect);
				let res = yield loginByToken();
				if(res.res == 1) {
					yield setLoginSession(res.data);
				} else {
					yield Actions.replace('login');
				}
			}
		},
		
		*login({navigation}, {select, put}) {
			const loginState = yield select(state => (state.login));
			let account = loginState.account;
			let password = loginState.password;
			if(!account) {
				return toast('center').show('账户不能为空');
			}
			if(!password) {
				return toast('center').show('密码不能为空');
			}
			let res = yield loginMix(account, password, -1);
			if(res.res == 1) {
				setLoginSession(res.data);
				Actions.replace(loginState.loginRedirect);
			} else {
				toast('center').show(res.msg);
			}
		},
		
	},
	
}